<template>
    <span class="star" @mouseout="mouseoutHandle">
        <span v-for="(starClass, index) in starClasses" :class="starClass" class="star-item"
              @mouseover="starItemHoverHandle(index)" @click="starItemClickHandle(index)" track-by="index">★</span><a
      href="#" v-if="this.score>0&&this.enableHover" class="star-clear" @click="clearScore">×</a>
    </span>
</template>

<script>
  const CLASS_ON = 'star-item-on';
  const CLASS_OFF = 'star-item-off';
  let tempScore = -1;// 用于悬停时临时存储分数
  export default {
    name: 'StarRating',
    props: {
      size: {
        type: Number,
        default: 5
      },
      score: {
        type: Number,
        default: 3
      },
      enableHover: {
        type: Boolean,
        default: false
      }
    },
    computed: {
      starClasses () {
        let result = [];
        for (let i = 0; i < this.score; i++) {
          result.push(CLASS_ON);
          // result.push({'star-item-on': true})
        }
        while (result.length < this.size) {
          result.push(CLASS_OFF);
          // result.push({'star-item-on': true});
        }
        return result;
      }
    },
    methods: {
      clearScore: function () {
        this.score = 0;
      },
      mouseoutHandle: function () {
        if (tempScore !== -1) {
          this.score = tempScore;
          tempScore = -1;
        }
      },
      starItemHoverHandle: function (idx) {
        if (!this.enableHover) {
          return;
        }
        if (tempScore === -1) {
          tempScore = this.score;
        }
        this.score = idx + 1;
      },
      starItemClickHandle: function () {
        tempScore = -1;
      }
    }
  }
</script>

<style>
  .star-item {
    font-size: 14px;
    margin: 0 2px;
    cursor: pointer;
    font-family: simsun;
  }

  .star-item-off {
    color: #999
  }

  .star-item-on {
    color: #f82
  }

  .star-clear {
    text-decoration: none;
    font-size: 24px;
    color: #c00;
    font-weight: bold;
  }
</style>
